//
//  MQStatusListViewModel.swift
//  SinaWeiBo
//
//  Created by 毛强 on 16/1/20.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SDWebImage

class MQStatusListViewModel: NSObject {
    
    var statuses:[MQStatusViewModel]?
  
    func loadUserData(isPullUp:Bool, completion:(isSuccess:Bool, count:Int)->()){
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        var sinceId:Int64 = 0
        var maxId:Int64 = 0
        if isPullUp{
            maxId = statuses?.last?.status?.id ?? 0
            if maxId > 0{
                maxId -= 1
            }
        }else{
            sinceId = statuses?.first?.status?.id ?? 0
        }
        let params = [
            "access_token" : MQUserAccountViewModel.shareUserAccountViewModel.accessToken!,
            "max_id":"\(maxId)",
            "since_id":"\(sinceId)"
        ]
        
        MQNetWorkTools.sharedTools.request(MQRequestMethod.GET, urlString: urlString, parameters: params) { (response, error) -> () in
            if error != nil{
                printfLog(error )
                completion(isSuccess: false, count: 0)
                return
            }
            
            if self.statuses == nil{
                self.statuses = [MQStatusViewModel]()
            }

            //printfLog((response as! [String : AnyObject]).description)
            //判断返回数据是否为字典类型
            guard let responseDict = response as? [String:AnyObject] else{
                printfLog("返回的数据不是字典")
                completion(isSuccess: false, count: 0)
                return
            }
            let statusDicts = responseDict["statuses"] as! [[String:AnyObject]]
            var tempArray = [MQStatusViewModel]()
            for dict in statusDicts{
                let status = MQStatus(dict: dict)
                
                let statusViewModel = MQStatusViewModel()
                statusViewModel.status = status
                tempArray.append(statusViewModel)
            }
            if isPullUp{
                self.statuses! += tempArray
                printfLog("上拉加载\(tempArray.count)条数据")

            }else{
                self.statuses! = tempArray + self.statuses!
                printfLog("下拉刷新出\(tempArray.count)条数据")
            }
            
//            self.tableView.reloadData()
//                        printfLog(tempArray)
            
            self.cacheSingleImage(tempArray, completion: completion)
//            completion(isSuccess: true)
            
        }
    }

    override var description:String{
        let keys = ["statuses"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    /**
     下载单张图片并且缓存在sandBox
     
     :param: tempArray <#tempArray description#>
     */
    private func cacheSingleImage(tempArray:[MQStatusViewModel], completion:(isSuccess:Bool, count:Int)->()){
        
        var countLength = 0
        let group = dispatch_group_create()
        for viewModel in tempArray{
            if viewModel.picUrls?.count != 1{
                continue
            }
            
            let urlString = viewModel.picUrls?.first?.thumbnail_pic!
            let url = NSURL(string: urlString!)
            dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(url!, options: [], progress: nil, completed: { (image , error , _, _, _) -> Void in
                if image != nil{
                    countLength += UIImagePNGRepresentation(image)!.length
//                    printfLog(image )
//                    printfLog("\(countLength / 1024)")
                }
                dispatch_group_leave(group)
            })
        }
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            //刷新数据
//            printfLog("单张图片下载完成，缓存大小为\(countLength / 1024)kb")
            completion(isSuccess: true, count: tempArray.count)
            
        })
    }
}


